package com.beici.waterghost.controller;

import com.beici.waterghost.model.node;
import com.beici.waterghost.model.resultes;
import com.beici.waterghost.model.user;
import com.beici.waterghost.service.impl.nodeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@CrossOrigin
@RestController
@RequestMapping("/node")
public class nodeController {

    @Autowired
    private nodeServiceImpl nodeService;

    @GetMapping("/getNodes")
    public resultes getNodes(){
        return nodeService.quertyNodeAll();
    }

    @DeleteMapping("/delNode/{nodeId}")
    public resultes delNode(@PathVariable("nodeId") Long nodeId){
        user principal = (user) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return nodeService.delNode(nodeId,principal.getUserId());
    }

    @GetMapping("/getDetailNode/{nodeId}")
    public resultes getDetailNode(@PathVariable("nodeId") Long nodeId){
        return nodeService.queryDetailsInfo(nodeId);
    }

    @PutMapping("/putNode")
    public resultes putNode(node node, HttpServletRequest request){
        try {
            user principal = (user) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            node.setUserId(principal.getUserId());
            node.setNodeIp(request.getRemoteHost());
            return nodeService.addNode(node);
        }catch (NullPointerException e){
            System.out.println(e.getMessage());
            return resultes.NoAuthenction();
        }
    }


    @PutMapping("/putNodeApp")
    public resultes putNodeApp(node node){
        try {
            user principal = (user) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            node.setUserId(principal.getUserId());
            node.setNodeIp("0.0.0.0");
            return nodeService.addNode(node);
        }catch (NullPointerException e){
            System.out.println(e.getMessage());
            return resultes.NoAuthenction();
        }
    }
}

